<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Request;

class Btc extends Controller
{
    public function index()
    {
        $data = Db::table('btc_block')->field(['height', 'hash', 'size', 'tx_count', 'reward_block', 'reward_fees', 'pool_name'])->order('id', 'desc')->limit(25)->select();
//        var_dump($data);
        return view('admin@btc/index', [
            'data' => $data
        ]);
    }

    public function getBlock($num)
    {
        // 非AJAX请求,则重定向到主页
        if (!Request::instance()->isAjax()) {
            $this->redirect('index/Index/index');
            return false;
        }
        $height = Db::table('btc_block')->max('height');
        if ($height == null) {
            $height = 0;
        }
        $sum = '';
//        var_dump($height + intval($num));
        for ($i = ($height+1); $i <= ($height + intval($num)); $i++) {
            $sum .= $i . ',';
        }
        $sum = rtrim($sum, ',');
//        var_dump($sum);exit;

//        $sum = '1,2,3';
        $url = 'https://chain.api.btc.com/v3/block/' . $sum;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        // 设定为不验证证书和host
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        $data = curl_exec($curl);
        // curl_close($curl);
        $info = json_decode($data, true); // JSON强转PHP数组,包括里面的对象
//         var_dump($info);

        if ($info['err_no'] > 0) {
            // 收集错误
            if ($info['err_no'] == 1) $errno = '找不到该资源';
            if ($info['err_no'] == 2) $errno = '参数错误';
            $data = [
                'status' => false,
                'msg' => $errno . ' : ' . $info['err_msg']
            ];
            return json($data);
        } elseif (empty($info['data'])) {
            $data = [
                'status' => false,
                'msg' => '查无数据,请提供正确的块高度'
            ];
            return json($data);
        } else {
            // 写入数据表
            $blockData = [];
            foreach ($info['data'] as $val) {
                $blockData[] = [
                    'height' => $val['height'],
                    'version' => $val['version'],
                    'mrkl_root' => $val['mrkl_root'],
                    'curr_max_timestamp' => $val['curr_max_timestamp'],
                    'timestamp' => $val['timestamp'],
                    'bits' => $val['bits'],
                    'nonce' => $val['nonce'],
                    'hash' => $val['hash'],
                    'prev_block_hash' => $val['prev_block_hash'],
                    'next_block_hash' => $val['next_block_hash'],
                    'size' => $val['size'],
                    'pool_difficulty' => $val['pool_difficulty'],
                    'difficulty' => $val['difficulty'],
                    'tx_count' => $val['tx_count'],
                    'reward_block' => $val['reward_block'],
                    'reward_fees' => $val['reward_fees'],
                    'created_at' => $val['created_at'],
                    'confirmations' => $val['confirmations'],
                    'pool_name' => $val['extras']['pool_name'],
                    'pool_link' => $val['extras']['pool_link']
                ];
            }
//            var_dump($blockData);exit;

            // 启动事务
            Db::startTrans();
            try {
                Db::table('btc_block')->insertAll($blockData);
                // 提交事务
                Db::commit();
                $data = [
                    'status' => true,
                    'datas' => $info['data']
                ];
//                echo '插入成功';
            } catch (\Exception $e) {
                $data = [
                    'status' => false,
                    'msg' => '批量插入数据有误,请重试!'
                ];
                // 回滚事务
                Db::rollback();
//                echo '插入失败';
            }
            // 记录日志

            // 并输出到前端
            return json($data);
        }
    }

    public function getOneBlock()
    {
        // 非AJAX请求,则重定向到主页
        if (!Request::instance()->isAjax()) {
            $this->redirect('index/Index/index');
            return false;
        }
        $height = Db::table('btc_block')->max('height');
        if ($height == null) {
            $height = 0;
        }
        $height += 1;

        $url = 'https://chain.api.btc.com/v3/block/' . $height;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        // 设定为不验证证书和host
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        $data = curl_exec($curl);
        // curl_close($curl);
        $info = json_decode($data,true); // 查得JSON数据 强转PHP数组
//        var_dump($info);

        if ($info['err_no'] > 0) {
            // 收集错误
            if ($info['err_no'] == 1) $errno = '找不到该资源';
            if ($info['err_no'] == 2) $errno = '参数错误';
            $data = [
                'status' => false,
                'msg' => $errno . ' : ' . $info['err_msg']
            ];
            return json($data);
        } elseif (empty($info['data'])) {
            $data = [
                'status' => false,
                'msg' => '查无数据,请提供正确的块高度'
            ];
            return json($data);
        } else {
            // 准备数据表
            $blockData['height'] = $info['data']['height'];
            $blockData['version'] = $info['data']['version'];
            $blockData['mrkl_root'] = $info['data']['mrkl_root'];
            $blockData['curr_max_timestamp'] = $info['data']['curr_max_timestamp'];
            $blockData['timestamp'] = $info['data']['timestamp'];
            $blockData['bits'] = $info['data']['bits'];
            $blockData['nonce'] = $info['data']['nonce'];
            $blockData['hash'] = $info['data']['hash'];
            $blockData['prev_block_hash'] = $info['data']['prev_block_hash'];
            $blockData['next_block_hash'] = $info['data']['next_block_hash'];
            $blockData['size'] = $info['data']['size'];
            $blockData['pool_difficulty'] = $info['data']['pool_difficulty'];
            $blockData['difficulty'] = $info['data']['difficulty'];
            $blockData['tx_count'] = $info['data']['tx_count'];
            $blockData['reward_block'] = $info['data']['reward_block'];
            $blockData['reward_fees'] = $info['data']['reward_fees'];
            $blockData['created_at'] = $info['data']['created_at'];
            $blockData['confirmations'] = $info['data']['confirmations'];
            $blockData['pool_name'] = $info['data']['extras']['pool_name'];
            $blockData['pool_link'] = $info['data']['extras']['pool_link'];

            $result = Db::table('btc_block')->insert($blockData);

            if ($result > 0) {
                $data = [
                    'status' => true,
                    'datas' => $info['data']
                ];
            } else {
                $data = [
                    'status' => false,
                    'msg' => '批量插入数据有误,请重试!'
                ];
            }
        }
        // 记录日志

        // 并输出到前端
        return json($data);
    }

    public function getHeight($height)
    {
        // 非AJAX请求,则重定向到主页
        if (!Request::instance()->isAjax()) {
            $this->redirect('index/Index/index');
            return false;
        }
        $data = Db::table('btc_block')->find($height);
        // var_dump($data);
        return json($data);
    }

    public function func1()
    {
        return view('admin@btc/func1');
    }

    public function func2()
    {
        return view('admin@btc/func2');
    }

}